package com.whosly.mysql.protocol.packet.impl;

import com.whosly.mysql.protocol.packet.jdbc.MySQLPacket;
import com.whosly.mysql.protocol.packet.util.NettyBufferUtil;
import io.netty.buffer.ByteBuf;

import java.io.Serializable;
import java.util.Arrays;

/**
 * @author fengyang
 * @date 2023/7/20 上午10:43
 * @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
 */
public class AuthSwitchResponsePacket extends MySQLPacket
        implements Serializable
{
    /**
     * 认证插件的数据，对于不同的插件这个数据的含义不一样。
     * <p>
     * 对于mysql_native_password来说，这里是密码经过约定算法hash过的结果
     */
    byte[] authMethodData;

    @Override
    public ByteBuf writeBuf(ByteBuf buffer)
    {
        NettyBufferUtil.writeUB3(buffer, calcPacketSize());
        buffer.writeByte(getPackId());

        buffer.writeBytes(authMethodData);

        return buffer;
    }

    @Override
    public void read(byte[] bodyBytes)
    {
        this.authMethodData = bodyBytes;
    }

    public byte[] getAuthMethodData() {
        return authMethodData;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final AuthSwitchResponsePacket that = (AuthSwitchResponsePacket) o;
        return Arrays.equals(authMethodData, that.authMethodData);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(authMethodData);
    }

    @Override
    public int calcPacketSize()
    {
        return authMethodData != null ? authMethodData.length : 0;
    }
}
